package org.wxd.common.utils;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;


/**
 * Created by wangxd on 2016/10/11.
 */
public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }


    public static ObjectMapper getMapper() {
        return mapper;
    }

    public static <T> T parse(String str, Class<?> collectionClass, Class<?> ... clazz){
        try {
            return mapper.readValue(str,mapper.getTypeFactory().constructParametricType(collectionClass,clazz));
        } catch (IOException e) {
            throw new JsonException(e.getMessage(),e);
        }
    }

    public static <T> T parse(String str, Class<T> clazz) {
        try {
            return (T) mapper.readValue(str,clazz);
        } catch (IOException e) {
            throw new JsonException(e.getMessage(),e);
        }
    }

    public static String stringify(Object target) {
        try {
            return mapper.writeValueAsString(target);
        } catch (JsonProcessingException e) {
            throw new JsonException(e.getMessage(),e);
        }
    }


}
